package com.cqw.sms;


import com.alibaba.fastjson.JSON;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;


@Component
public class MWSmsUtil {

    private static final Logger log = LoggerFactory.getLogger(MWSmsUtil.class);

    public boolean sendMsg(String url,String userName, String password, String mobile, String content) {
        boolean sendResult = false;
        Response response = null;
        SimpleDateFormat sdf = new SimpleDateFormat("MMddHHmmss");
        String timestamp = sdf.format(new Date());
        try {
            //String pwd = MD5Util.getSignMin(password);
            String urlEncodeContent = URLEncoder.encode(content, "UTF-8");

            //发送http请求，并接收http响应
            response = doPostRequest(url, userName, password, urlEncodeContent, timestamp, mobile);
            //解析响应字符串
            log.info("发送手机号： {}，结果：{}", mobile, response);
            if (response.isSuccessful()) {
                sendResult = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("发送验证码出错：{}", JSON.toJSONString(e));
        } finally {
            if (response != null) {
                response.close();
            }
//            //记录短信的log
//            SendRecord sendRecord = new SendRecord();
//            sendRecord.setId(Base58UUID.newBase58UUID());
//            sendRecord.setAccount(storeCode);
//            sendRecord.setReceivePhone(mobile);
//            sendRecord.setTemplateCode(templateCode);
//            sendRecord.setLogin(customerId);
//            sendRecord.setContent(content);
//            sendRecord.setResult(String.valueOf(response));
//            sendRecord.setSendTime(new Date());
//            sendRecordRepository.save(storeCode, sendRecord);
        }
        return sendResult;
    }

    /**
     * 发送请求
     *
     * @param url              梦网发送url
     * @param userid           账号
     * @param pwd              密码
     * @param urlEncodeContent 短信内容
     * @param timestamp
     * @param mobile
     * @return
     * @throws IOException
     */
    private Response doPostRequest(String url, String userid, String pwd, String urlEncodeContent, String timestamp, String mobile) throws IOException {
        MWParamsVM mwParamsVM = MWParamsVM.from(userid, pwd, urlEncodeContent, mobile, timestamp);
        OkHttpClient client = new OkHttpClient();
        System.out.println(JSON.toJSONString(mwParamsVM));
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(mwParamsVM));
        okhttp3.Request request = new okhttp3.Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .build();
        return client.newCall(request).execute();
    }
}
